const _ = require("lodash");

/**
 * 连错惩罚 + 热冷融合评分策略
 * @param {Array<{ time: string, number: string }>} temp
 * @returns {string[]}
 */
function select32NumbersByS2(temp) {
  const allNumbers = Array.from({ length: 49 }, (_, i) =>
    (i + 1).toString().padStart(2, "0")
  );

  const freqMap = {};
  const lastAppearMap = {};
  const wrongStreakMap = {};

  // 初始化连续不中
  allNumbers.forEach((num) => (wrongStreakMap[num] = 0));

  // 从后往前走，模拟最近连续不中次数
  for (let i = temp.length - 1; i >= 0; i--) {
    const num = temp[i].number;
    allNumbers.forEach((n) => {
      if (n === num) {
        wrongStreakMap[n] = 0;
      } else {
        wrongStreakMap[n]++;
      }
    });

    freqMap[num] = (freqMap[num] || 0) + 1;
    lastAppearMap[num] = i;
  }

  // 构造评分：热度分 - 错误惩罚分
  const scoredNumbers = allNumbers.map((n) => {
    const freq = freqMap[n] || 0;
    const gap = lastAppearMap[n] !== undefined ? temp.length - 1 - lastAppearMap[n] : temp.length;
    const wrong = wrongStreakMap[n] || 0;

    const score = freq * 2 + gap * 1 - wrong * 1.2; // ⬅️ 权重可调
    return { number: n, score };
  });

  // 排序 + 取前 32 个高分号码
  const final = scoredNumbers
    .sort((a, b) => b.score - a.score)
    .slice(0, 32)
    .map((x) => x.number);

  return final;
}

module.exports = select32NumbersByS2;
